<template>
    <div id="add-edit-risk-point">
        <el-dialog
            :title="titleCon"
            v-model="isUseDialog" 
            draggable 
            :close-on-click-modal="false" 
            width="60%" 
            :before-close="handleClose"
            :destroy-on-close="true"
            @close="clean"
        >
            <el-form :model="ruleForm" ref="ruleFormRef" size="default" label-width="140px" :rules="rules">
                <el-row>
                    <el-col :xs="24" :sm="24" :md="24" :lg="24" :xl="24" class="mb20">
                        <el-form-item label="风险管控分析单元" prop="l_AnalysisUnitIds">
                            <el-select 
                                filterable 
                                v-model="ruleForm.l_AnalysisUnitIds" 
                                placeholder="请选择风险分析单元" 
                                @change="analyChange"
                                multiple
                                collapse-tags
                                value-key="id"
                            >
                                <el-option
                                    v-for="item in analyOption"
                                    :key="item.id"
                                    :label=" item.v_RiskPartitionName ? item.v_RiskPartitionName + '——' + item.v_Name : item.v_Name"
                                    :value="item.id"
                                />
                            </el-select>
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
            <template #footer>
                <el-button @click="cancelUseClick">取消</el-button>
                <el-button type="primary" :disabled="repeatDis" :loading="repeatDis" @click="submitForm(ruleFormRef)">提交</el-button>
            </template>
        </el-dialog>
    </div>
</template>
<script lang="ts">
import { defineComponent, ref, reactive , computed , toRefs , toRaw , watch } from 'vue';
import { FormInstance, FormRules, ElButton, ElCol, ElDialog, ElForm, ElRow } from 'element-plus';
import { SMSDCAnalysisUnitList , SMSIPPathUnitBathAddOrUpdate , SMSIPPathUnitList } from '/@/api/centerControl/sms';
/*** 定义接口基础数据类型 */
interface formType {
    repeatDis: Boolean,
    ruleForm: ruleFormType,
}
/*** form 表单数据类型 */
type ruleFormType = {
    l_AnalysisUnitIds: any, // 风险管控分析单元Id
}
export default defineComponent( {
    name: 'add-edit-risk-point',
    components: {},
    props: {
        isUseDialog:{
            type: Boolean,
            default: false,
        },
        repairInfo: {
            type: String,
            default: ''
        }
    },
    setup(props,ctx){
        const titleCon = ref();
        const ruleFormRef = ref();
        const analyOption = ref();

        /*** state 引用接口定义基础数据初始值 */
        const state = reactive < formType > ({
            repeatDis: false,
            ruleForm: {} as ruleFormType
        })

        /*** 基础验证 rules */
        const rules = reactive < FormRules > ({
            /*** 放置验证 */
            // 风险管控分析单元
            l_AnalysisUnitIds: [
				{ required: true, message: '请选择风险分析单元', trigger: 'change' },
			],
        })

        /*** handleClose 关闭按钮点击事件 */
        const handleClose = () => {
            cancelUseClick();
        }

        /*** cancelUseClick 取消事件 */
        const cancelUseClick = () => {
            ctx.emit('cancelFunClick');
        }

        /*** submitForm 提交事件 */
        const submitForm = (formEl: FormInstance | undefined) => {
            if(!formEl) return
            formEl.validate( async (valid) => { 
                if(valid){
                    let param:any = toRaw(state.ruleForm)
                    let setArr: any = [];
                    param.l_AnalysisUnitIds.map((item: any) => {
                        setArr.push(item);
                    });
                    let parData: any = {};
                    parData.l_IPPathId = JSON.parse(props.repairInfo).id;
                    parData.l_AnalysisUnitIds = setArr;
                    state.repeatDis = true;
                    try{
                        let res: any = await SMSIPPathUnitBathAddOrUpdate(parData);
                        if(res.success){
                            state.repeatDis = false;
                            ctx.emit('updateData');
                            ctx.emit('controlFunClick');
                        }else{
                            state.repeatDis = false;
                            ctx.emit('controlFunClick'); 
                        }
                    }catch(error){ state.repeatDis = false; }
                }else{
                    console.log('error submit!')
					return false;
                }
            })
        }

        /*** clean 清空数据 */
        const clean = () => {
            ruleFormRef.value.resetFields()
        }

        /*** getData 获取数据 */
        const getData = async() => {
            let res:any = await SMSDCAnalysisUnitList({isUse: true});
            if(res.success) analyOption.value = res.data;
        }

        /*** analyChange 风险分析单元改变事件 */
        const analyChange = (val: any) => {
            // if(val && val.length !== 0){
            //     let setArr: any = [];
            //     val.map((item: any) => {
            //         setArr.push(item.id);
            //     });
            //     state.ruleForm.l_AnalysisUnitIds = setArr;
            // }
        }

        /*** 获取已选的风险分析单元 */
        const getChoseFun = async(id: Number) => {
            let param: any = {};
            param.l_IPPathId = id;
            let res: any = await SMSIPPathUnitList(param);
            if(res.success && res.data.length !== 0){
                let ids: any = [];
                res.data.map((i: any) => {
                    ids.push(i.l_AnalysisUnitId);
                });
                state.ruleForm.l_AnalysisUnitIds = ids;
            }
        }

        /*** 监听isUseDialog的变化 */
        watch(() => props.isUseDialog,async(newVal) => {
            if(newVal){
                let getVal = JSON.parse(props.repairInfo);
                titleCon.value = '选择风险分析单元';
                await getData();
                getChoseFun(getVal.id);
            }
        })

        /*** isUseDialog 响应弹窗的关闭  */
        const isUseDialog = computed(() => {
            return props.isUseDialog
        })

        return {
            handleClose,
            submitForm,
            cancelUseClick,
            clean,
            ruleFormRef,
            titleCon,
            ...toRefs(state),
            isUseDialog,
            rules,
            analyChange,
            analyOption,
        }
    },
} )
</script>
<style scoped lang="scss">
:deep(.el-cascader){
    width: 100%;
}
:deep(.el-select){
    width: 50%!important;
}
:deep(.el-input){
    width: 100%;
}
</style>